﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using System.Web;

namespace CoolCode.DataSource
{
    public class DBFactory
    {
        private static IDataProvider instance;

        public static IDataProvider CreateInstance()
        {
            if (instance == null)
            {
                string typeName = ConfigurationManager.AppSettings["DBType"];
                string assemblyName = ConfigurationManager.AppSettings["DBAssembly"];
                instance = CreateInstance(typeName, assemblyName);
            }
            return instance;
        }

        public static IDataProvider CreateInstance(string typeName, string assemblyName)
        {
            IDataProvider _instance;
            string rootPath = string.Empty;

            try
            {
                //if web application
                rootPath = HttpRuntime.BinDirectory;
            }
            catch
            {
                //if remoting application
                rootPath = string.Empty;
            }

            Assembly assembly = Assembly.LoadFrom(rootPath + assemblyName);
            _instance = assembly.CreateInstance(typeName) as IDataProvider;

            return _instance;
        }
    }
}
